package com.binvshe.binvshe.contacts;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.binvshe.binvshe.app.storagemanager.SpDao;
import com.pachong.android.frameworkbase.utils.GsonUtils;
import com.pachong.android.frameworkbase.utils.RegularUtils;
import com.pachong.android.frameworkbase.utils.SLog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取手机联系人的service
 * <p>
 * 因为获取手机联系人太慢，就将此功能放在一个service中。
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016/11/1 13:53
 * @Version: 1.0.0
 */
public class ContactsService extends IntentService {
    public static final String TAG = ContactsService.class.getSimpleName();

    public static final String ACTION_GET_CONTACTS = "action_get_contacts";


    public static void start(Context context, String action) {
        Intent intent = new Intent(context, ContactsService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    public ContactsService() {
        super("ContactsService");
        SLog.e(TAG, "ContactsService");
    }

    boolean isGettingContacts = false;


    @Override
    protected void onHandleIntent(Intent intent) {
        SLog.e(TAG, "onHandleIntent");
        switch (intent.getAction()) {
            case ACTION_GET_CONTACTS:
                if (!isGettingContacts) {
                    isGettingContacts = true;
                    List<Contact> contacts = getContactsInfo();
                    SLog.e(TAG, "获取联系人结束 一共 " + contacts.size());
                    String contactsStr = GsonUtils.object2String(contacts);
                    SpDao.setCacheContacts(this, contactsStr);

                   /* List<Contact> list = GsonUtils.string2ObjecetList(SpDao.getCacheContacts(this), Contact[].class);
                    if (list != null && list.size() > 0) {
                        for (Contact contact : list) {
                            SLog.e(TAG, "contact == " + contact);
                        }
                    }*/
                    isGettingContacts = false;
                    EventBus.getDefault().post(new ContactMessage());
                }
                break;
        }

    }


    public String makePhoneNumClear(String num) {
        if (!TextUtils.isEmpty(num) && num.length() >= 11) {
            // 取后面11位
            num = num.replace(" ", "");
            num = num.replace("-", "");
            if(num.length() >= 11){
                num = num.substring(num.length() - 11);
            }
            if (RegularUtils.isMobileExact(num)) {
                return num;
            }
            return null;
        }
        return null;
    }


    /**
     * 获取手机联系人以及联系人的电话号码
     * 没有电话号码则过滤
     *
     * @return
     */
    public List<Contact> getContactsInfo() {
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        int contactIdIndex = 0;
        int nameIndex = 0;
        List<Contact> contacts = new ArrayList<>();
        if (cursor != null) {

            if (cursor.getCount() > 0) {
                contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            }

            while (cursor.moveToNext()) {
                String contactId = cursor.getString(contactIdIndex);
                String name = cursor.getString(nameIndex);

            /*
             * 查找该联系人的phone信息
             */
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                        null, null);
                int phoneIndex = 0;
                if (phones != null && phones.getCount() > 0) {
                    phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phoneIndex);
                        String phoneNum = makePhoneNumClear(phoneNumber);
                        if (!TextUtils.isEmpty(phoneNum)) {
                            Contact contact = new Contact(phoneNum, name);
                            contacts.add(contact);
                        }
                    }
                }
            }

        }

        return contacts;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    public static class Contact {

        public Contact(String phoneNum, String name) {
            this.phoneNum = phoneNum;
            this.name = name;
        }

        String phoneNum;
        String name;

        @Override
        public String toString() {
            return "Contact{" +
                    "phoneNum='" + phoneNum + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

}
